package com.library.service;

import com.library.dao.ReaderInfoDao;
import com.library.domain.ReaderInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserModuleServiceImpl implements UserModuleService {
    @Resource
    private ReaderInfoDao readerInfoDao;

    @Override
    public int readerRegister(ReaderInfo readerInfo) throws NullPointerException{
       boolean isExist= usernameIsExist(readerInfo.getUsername());
       if(isExist){
           /*
           * 用户名存在不可以注册
           * */
           return -1;
       } else{
           return readerInfoDao.insertOne(readerInfo);
       }
    }


    @Override
    public int readerLogin(String username, String password) throws NullPointerException{
        /*
         * 1、判断用户是否存在
         * */

        List<ReaderInfo> lr = readerInfoDao.selectForLogIn(username);
        if (lr.size() == 0) {
            //返回结果为0，用户名不存在，访问失败
            return -1;
        } else if (lr.size() == 1) {
            //用户名存在，比较密码
            ReaderInfo readerInfo=lr.get(0);

            if(readerInfo.getPassword().equals(password)){
                return lr.size();
            }else{

                return 0;
            }
        } else {
            //暂时使用空指针异常代替
            throw new NullPointerException("数据库需要维修！");
        }

    }

    @Override
    @Transactional
    /*
    * 增删改需要添加事务机制
    * */
    public int readerResetPassword(String username, String password) throws NullPointerException{

       List<ReaderInfo>lr= readerInfoDao.selectForLogIn(username);
       /*
       * 当用户名存在
       * */
       if(lr.size()==1){
           //用户名存在，前端和controller判定密码格式正确，执行更新操作
          int count= readerInfoDao.resetPassword(username,password);
           if(count==1){
               return readerInfoDao.resetPassword(username,password);
           }else{
               throw new NullPointerException("更新失败");
           }
       }else if(lr.size()==0){
           return -1;
       }else{
           throw new NullPointerException("数据库需要维修");
       }
    }

    /*
    * 判断用户名是否存在的方法
    *
    * */
    public boolean usernameIsExist(String username) throws NullPointerException{
       List<ReaderInfo> lr= readerInfoDao.selectForLogIn(username);
       if(lr.size()==1){
          return true;
       } else{
           if(lr.size()==0){
           return false;
           }else{
               throw new NullPointerException("数据库需要维修");
           }
       }

    }



}








